package org.example.batisDemo;


import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.example.pojo.Fqm;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/*
 * @Description: mybatis demo1
 * 快速入门
 *
 */
public class MyBatisDemo1 {

    private static final String RESOURCE = "mybatis-demo1-config.xml";
    private static SqlSession SqlSession;

    public MyBatisDemo1() {
        try {
            this.loadSession();
        } catch (IOException e) {
            System.out.println("加载session失败");
            e.printStackTrace();
        }
    }

    // 加载session
    private void loadSession() throws IOException {
        // 加载mybatis配置文件
        InputStream inputStream = Resources.getResourceAsStream(RESOURCE);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        // 获取sqlSession 对象，可以执行sql语句
        MyBatisDemo1.SqlSession = sqlSessionFactory.openSession();
        System.out.println("加载session成功");
    }

    // 查询
    public void queryAll() {
        // 查询：
        List<Fqm> fqmList = MyBatisDemo1.SqlSession.selectList("test.selectAll");
        System.out.println(fqmList);
    }

    //  关闭连接
    public static void close() {
        if (SqlSession != null) {
            SqlSession.close();
            System.out.println("关闭session成功");
        }
    }
}
